import { defineStore } from 'pinia';
import {
  login as userLogin,
  getUserInfo,
  LoginData,
  getWarehours
} from '@/api/user';
import { setToken, clearToken } from '@/utils/auth';
import { removeRouteListener } from '@/utils/route-listener';
import { UserState } from './types';
import useAppStore from '../app';

const useUserStore = defineStore('user', {
  state: (): UserState => ({
    userName: '',
    menus: [],
    permissions: [],
    role: ''
  }),

  getters: {
    userInfo(state: UserState): UserState {
      return { ...state };
    },
  },

  actions: {
    switchRoles() {
      return new Promise((resolve) => {
        this.role = this.role === 'user' ? 'admin' : 'user';
        resolve(this.role);
      });
    },
    // Set user's information
    setInfo(partial: Partial<UserState>) {
      this.$patch(partial);
    },

    // Reset user's information
    resetInfo() {
      this.$reset();
    },

    // Get user's information
    async info() {
      const data = await getUserInfo();
      localStorage['user.info'] = JSON.stringify(data);
      this.setInfo(data);
    },

    // Login
    async login(loginForm: LoginData) {
      const data = await userLogin(loginForm);
      this.setInfo(data);
      setToken(data.token, data.userId);
      localStorage['user.login'] = JSON.stringify(data);
      // clearToken();
      return data;
    },
    logoutCallBack() {
      const appStore = useAppStore();
      this.resetInfo();
      clearToken();
      removeRouteListener();
      appStore.clearServerMenu();
    },
    // Logout
    async logout() {
      this.logoutCallBack();
    },
  },
});

export default useUserStore;
